﻿Public Partial Class frm_PortSchedulerNew
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData()
    Dim clsFc As New ClassFunction

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not (IsPostBack) Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "PORT SCHEDULER"
            ViewState("WharfBulk") = clsGet.Get_WharfAll("B")
            ViewState("WharfLiquid") = clsGet.Get_WharfAll("L")
            btnScheduler.Visible = False
            lbAlert.Visible = False
            txtDateTo.Text = Date.Now.ToString("dd MMM yyyy")
            LoadData(txtDateTo.Text)
        End If
    End Sub

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click
        LoadData()
    End Sub
    Private Sub btnReloadDataDummy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReloadDataDummy.Click
        LoadData()
    End Sub

    Private Sub LoadData(Optional ByVal dateTo As String = "")
        Dim DateStart As String = "20000000"
        Dim DateEnd As String = "29991230"
        If (dateTo <> "") Then
            DateEnd = dateTo
        End If
        If (txtDate.Text.Trim() <> "") Then
            Try
                DateStart = CDate(txtDate.Text).ToString("yyyyMMdd")
            Catch ex As Exception
                If ((txtDate.Text.Split(" ")(0) & " " & txtDate.Text.Split(" ")(1)) = "29 Feb") Then
                    DateStart = txtDate.Text.Split(" ")(2) & "0229"
                End If
            End Try

        End If
        If (txtDateTo.Text.Trim() <> "") Then
            Try
                DateEnd = CDate(txtDateTo.Text).ToString("yyyyMMdd")
            Catch ex As Exception
                If ((txtDateTo.Text.Split(" ")(0) & " " & txtDateTo.Text.Split(" ")(1)) = "29 Feb") Then
                    DateEnd = txtDateTo.Text.Split(" ")(2) & "0229"
                End If
            End Try

        End If
        Dim ds As DataSet = clsGet.Get_Booking_Wharf(DateStart, DateEnd, ddlWharf.SelectedValue)
        If (ds.Tables(0).Rows.Count > 0) Then
            btnScheduler.Visible = True
            lbAlert.Visible = False
        Else
            btnScheduler.Visible = False
            lbAlert.Visible = True
        End If
        gridScheduler.DataSource = ds
        gridScheduler.DataBind()
    End Sub

    Private Sub gridScheduler_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridScheduler.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If e.CommandName = "cmdShifting" Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_Iframe_Shifting').src = '../FormPopup/Frm_ManageShifting.aspx" & Request.Url.Query & "';", True)
            Session("Shifting") = gridScheduler.DataKeys(Index).Values("Booking_no")
            Session("PORT") = ddlWharf.Text
            Session("isFromSchedule") = Nothing
            ModalPopupExtender1.Show()
        End If
    End Sub

    Private Sub gridScheduler_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridScheduler.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim ddlWharfx As DropDownList = CType(e.Row.FindControl("ddlWharf"), DropDownList)
            With ddlWharfx
                .ClearSelection()
                .DataTextField = "Wharf"
                .DataValueField = "BookingWharf"
                If (ddlWharf.SelectedValue = "B") Then
                    .DataSource = ViewState("WharfBulk")
                Else
                    .DataSource = ViewState("WharfLiquid")
                End If
                .DataBind()
                .Items.Insert(0, "<--Wharf-->")
                .Items(0).Value = "0"
            End With

            If (gridScheduler.DataKeys(e.Row.RowIndex).Values("Booking_Time") & "" <> "") And (gridScheduler.DataKeys(e.Row.RowIndex).Values("Booking_Date") & "" <> "") Then
                Dim txtDateTo As TextBox = CType(e.Row.FindControl("txtDateTo"), TextBox)
                Dim txtBookingTimeEnd As TextBox = CType(e.Row.FindControl("txtTimeBookingEnd"), TextBox)
                Dim stardardTime As Integer = CInt(gridScheduler.DataKeys(e.Row.RowIndex).Values("StandardTime"))
                Dim HourStart As Integer = CInt(gridScheduler.DataKeys(e.Row.RowIndex).Values("Booking_Time").ToString().Split(":")(0))
                Dim HourDivision As Integer = 24 - HourStart
                If (HourDivision >= stardardTime) Then
                    'วันเดียวเสร็จ
                    txtDateTo.Text = gridScheduler.DataKeys(e.Row.RowIndex).Values("Date_From")
                    txtBookingTimeEnd.Text = (HourStart + stardardTime).ToString("00") & ":" & gridScheduler.DataKeys(e.Row.RowIndex).Values("Booking_Time").ToString().Split(":")(1)
                Else
                    'ข้ามวัน
                    Dim DateCount As Integer = ((stardardTime - HourDivision) \ 24) + 1
                    txtDateTo.Text = CDate(gridScheduler.DataKeys(e.Row.RowIndex).Values("Date_From")).AddDays(DateCount).ToString("dd MMM", New Globalization.CultureInfo("en-US")) & CDate(gridScheduler.DataKeys(e.Row.RowIndex).Values("Date_From")).AddDays(DateCount).ToString(" yyyy")
                    txtBookingTimeEnd.Text = ((HourStart + stardardTime) Mod 24).ToString("00") & ":" & gridScheduler.DataKeys(e.Row.RowIndex).Values("Booking_Time").ToString().Split(":")(1)
                End If


                e.Row.Cells(8).Text = gridScheduler.DataKeys(e.Row.RowIndex).Values("Booking_Date") & " : " & gridScheduler.DataKeys(e.Row.RowIndex).Values("Booking_Time")

            End If
            e.Row.Cells(7).Text = gridScheduler.DataKeys(e.Row.RowIndex).Values("Date_From").ToString.Substring(0, 2) & "-" & gridScheduler.DataKeys(e.Row.RowIndex).Values("Date_To")
            e.Row.Cells(9).Text = e.Row.Cells(9).Text & " hours"
        End If
    End Sub

    Private Sub btnScheduler_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnScheduler.Click
        If (checkGridValue()) Then
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase
            Dim clsFc As New ClassFunction
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Dim User_Create As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
            Application.Lock()
            conn.Open()
            tran = clsDB.BeginTran(conn)
            Dim dt As DataTable = ViewState("DataWharf")
            For Each dr As DataRow In dt.Rows
                If (clsFc.InsertBooking_Wharf(dr.Item("Booking_no"), dr.Item("BookingWharf"), dr.Item("Date_From"), dr.Item("Date_To"), dr.Item("TimeStart"), dr.Item("TimeEnd"), dr.Item("Remark"), User_Create, dr.Item("DateStart"), dr.Item("DateEnd"), "N", "", "", conn, tran) < 1) Then
                    condition = False
                End If
            Next

            If (condition) Then
                clsDB.CommitTran(tran)
                Dim Mail As String = ""
                For Each dr As DataRow In dt.Rows
                    Dim dtBooking As DataTable = clsGet.Get_BookingOneRecord(dr.Item("Booking_no")).Tables(0)
                    Dim Wharf As String = clsGet.Get_WharfName(dr.Item("BookingWharf"))
                    SendMail(clsGet.Get_EmailForSendAgent(dr.Item("Booking_no")), GenBody("รายการ Booking ได้ถูกจัดคิวการใช้บริการท่าเรือแล้ว", dr.Item("Booking_no"), dtBooking.Rows(0).Item("MAgent_no") & "-" & dtBooking.Rows(0).Item("MAgent_name"), dtBooking.Rows(0).Item("Vehicle_no") & "-" & dtBooking.Rows(0).Item("Vehicle_Text"), dtBooking.Rows(0).Item("Date_From") & "-" & dtBooking.Rows(0).Item("Date_To"), Wharf, dr.Item("Date_From") & " " & dr.Item("TimeStart"), dr.Item("Date_To") & " " & dr.Item("TimeEnd")))
                Next
                LoadData()
                ViewState("DataWharf") = CreateDataTable()
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเรียบร้อย');", True)
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End If
            Application.UnLock()
            conn.Dispose()
        End If
    End Sub

    Private Function checkGridValue()
        Dim dt As DataTable = CreateDataTable()
        For i As Integer = 0 To gridScheduler.Rows.Count - 1
            Dim chk As CheckBox = CType(gridScheduler.Rows(i).FindControl("chkSelect"), CheckBox)
            If (chk.Checked) Then
                Dim ddlWharfg As DropDownList = CType(gridScheduler.Rows(i).FindControl("ddlWharf"), DropDownList)
                If (ddlWharfg.SelectedValue = "0") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Wharf ของ Booking no. " & gridScheduler.DataKeys(i).Values("Booking_no") & "" & "');", True)
                    Return False
                End If
                Dim txtDateg As TextBox = CType(gridScheduler.Rows(i).FindControl("txtDate"), TextBox)
                Dim txtDateTog As TextBox = CType(gridScheduler.Rows(i).FindControl("txtDateTo"), TextBox)
                Dim txtTimeStart As TextBox = CType(gridScheduler.Rows(i).FindControl("txtTimeBookingStart"), TextBox)
                Dim txtTimeEnd As TextBox = CType(gridScheduler.Rows(i).FindControl("txtTimeBookingEnd"), TextBox)
                Dim txtRemark As TextBox = CType(gridScheduler.Rows(i).FindControl("txtRemark"), TextBox)
                If (txtDateg.Text.Trim() = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุวันที่เริ่มต้นของ Booking no. " & gridScheduler.DataKeys(i).Values("Booking_no") & "" & "');", True)
                    Return False
                End If
                If (txtDateTog.Text.Trim() = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุวันที่สิ้นสุดของ Booking no. " & gridScheduler.DataKeys(i).Values("Booking_no") & "" & "');", True)
                    Return False
                End If
                If (txtTimeStart.Text.Trim().Replace(":", "") = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเวลาเริ่มต้นของ Booking no. " & gridScheduler.DataKeys(i).Values("Booking_no") & "" & "');", True)
                    Return False
                End If
                If (txtTimeEnd.Text.Trim().Replace(":", "") = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเวลาสิ้นสุดของ Booking no. " & gridScheduler.DataKeys(i).Values("Booking_no") & "" & "');", True)
                    Return False
                End If
                If (CDate(txtDateg.Text) > CDate(txtDateTog.Text)) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ช่วงเวลารายการ Booking no. " & gridScheduler.DataKeys(i).Values("Booking_no") & "" & " ไม่ถูกต้อง');", True)
                    Return False
                End If
                Dim dr As DataRow = dt.NewRow()
                dr.Item("Booking_no") = gridScheduler.DataKeys(i).Values("Booking_no")
                dr.Item("BookingWharf") = ddlWharfg.SelectedValue
                dr.Item("Date_From") = txtDateg.Text
                dr.Item("Date_To") = txtDateTog.Text
                Try
                    dr.Item("DateStart") = CDate(txtDateg.Text).ToString("dd/MM/yyyy")
                Catch ex As Exception
                    dr.Item("DateStart") = "29/02/" & txtDateg.Text.Split(" ")(2)
                End Try
                Try
                    dr.Item("DateEnd") = CDate(txtDateTog.Text).ToString("dd/MM/yyyy")
                Catch ex As Exception
                    dr.Item("DateEnd") = "29/02/" & txtDateTog.Text.Split(" ")(2)
                End Try

                dr.Item("TimeStart") = txtTimeStart.Text
                dr.Item("TimeEnd") = txtTimeEnd.Text
                dr.Item("Remark") = txtRemark.Text
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If
        Next
        ViewState("DataWharf") = dt
        Return True
    End Function

    Private Function CreateDataTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("Booking_no", GetType(String))
        dt.Columns.Add("BookingWharf", GetType(String))
        dt.Columns.Add("Date_From", GetType(String))
        dt.Columns.Add("Date_To", GetType(String))
        dt.Columns.Add("DateStart", GetType(String))
        dt.Columns.Add("DateEnd", GetType(String))
        dt.Columns.Add("TimeStart", GetType(String))
        dt.Columns.Add("TimeEnd", GetType(String))
        dt.Columns.Add("Remark", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub

    Private Function GenBody(ByVal str As String, ByVal booking_no As String, ByVal Agent As String, ByVal Vessel As String, ByVal Laycan As String, ByVal Wharf As String, ByVal Berth As String, ByVal Depart As String) As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td align='left'><font class='White-Style' font-weight:bold style='color:#000000'>" & str & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"

        HTML &= "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Booking No. :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & booking_no & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Sold To :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Agent & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Vessel :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Vessel & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Lay Can\Lay Day :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Laycan & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>WHARF :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Wharf & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>PLAN BERTH :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Berth & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>PLAN DEPART :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Depart & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"
        Return HTML
    End Function

    Private Function SendMail(ByVal mail As String, ByVal Body As String) As Boolean
        Dim test As String = clsFc.sendmail(mail, "", "iPORT", Body, "")
        If (test <> "") Then
            Return True
        Else
            Return False
        End If
    End Function

    
End Class